import axios from 'axios'
import router from '@/router/routers'
import store from '../store'
// import { getToken } from '@/utils/auth'
import Config from '@/settings'
import Cookies from 'js-cookie'
import { Toast } from 'vant'
// 创建axios实例
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'production' ? process.env.VUE_APP_BASE_API : '/', // api 的 base_url
  // baseURL: process.env.VUE_APP_BASE_API,
  timeout: Config.timeout // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    console.log('实际请求地址：', config.baseURL + config.url)
    if (config.headers['initialValue']) {
      config.headers['Authorization'] = config.headers['initialValue'] // 让每个请求携带自定义token 请根据实际情况自行修改
    } else if (localStorage.getItem('tokenValue')) {
      // config.headers['Authorization'] = '44456' // 让每个请求携带自定义token 请根据实际情况自行修改
      config.headers['Authorization'] = localStorage.getItem('tokenValue') // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    config.headers['Content-Type'] = 'application/json'
    return config
  },
  error => {
    Promise.reject(error)
  }
)
// response 拦截器
service.interceptors.response.use(
  response => {
    if (response && response.data.success === false) {
      if (response.data.error.name === 'OPERATOR_NOT_LOGIN') { // 超时
        Toast('当前登录状态已过期，请重新登录！')
        setTimeout(() => {
          router.push({ path: '/login' })
          localStorage.clear() // 清除token
          Cookies.remove('Authorization')
          window.name = ''
          window.location.reload() // 刷新页面
          return response.data
        }, 1000)
      } else if (response && response.data.error.name === 'DO_NOT_HAVE_LOGIN_AUTHORITY') { // 没登录权限
        Toast.fail('你没有登录权限')
        setTimeout(() => {
          // localStorage.clear() // 清除token
          // window.name = ''
          location.href = process.env.VUE_APP_PORTAL_URL // 返回门户
          return response.data
        }, 2000)
      } else if(response && response.data.error.name === 'SHOW_FAIL') {
        Toast.fail(response.data.error.message)
        return response.data
      }else if (response && localStorage.getItem('typeOptions')==='ignoreMistakes') { // 没权限
        return response.data
      }else {
        Toast.fail(response.data.error.message)
        return response.data
      }
    } else {
      if (response.headers['content-disposition']) {
        // 解码
        const fileName = decodeURI(response.headers['content-disposition'])
        const regFileNames = fileName.match(/=(.*)$/)[1] // 文件名称  截取=后面的文件名称
        response.data.name = regFileNames
      }
      return response.data
    }
  },
  error => {
    // 兼容blob下载出错json提示
    if (error.response.data instanceof Blob && error.response.data.type.toLowerCase().indexOf('json') !== -1) {
      // console.log('公共', error)
      const reader = new FileReader()
      reader.readAsText(error.response.data, 'utf-8')
      reader.onload = function(e) {
        const errorMsg = JSON.parse(reader.result).message
        Toast.fail({
          message: errorMsg,
          duration: 5000
        })
      }
    } else {
      let code = 0
      try {
        code = error.response.data.status
      } catch (e) {
        if (error.toString().indexOf('Error: timeout') !== -1) {
          Toast.fail({
            message: '网络请求超时',
            duration: 5000
          })
          return Promise.reject(error)
        }
      }
      console.log(code)
      if (code) {
        if (code === 401) {
          this.$Toast.fail('系统出错请联系管理员')
        } else if (code === 403) {
          router.push({ path: '/401' })
        } else {
          const errorMsg = error.response.data.message
          if (errorMsg !== undefined) {
            Toast.fail({
              message: errorMsg,
              duration: 5000
            })
          }
        }
      } else {
        Toast.fail({
          message: '接口请求失败',
          duration: 5000
        })
      }
    }
    return Promise.reject(error)
  }
)
export default service
